package com.xiaoyu.studyworkspace.common.websocketclient;

import cn.hutool.json.JSONUtil;
import com.xiaoyu.studyworkspace.common.kapaentity.websocket.*;
import com.xiaoyu.studyworkspace.dto.RecordDTO;
import com.xiaoyu.studyworkspace.service.PredictionService;
import com.xiaoyu.studyworkspace.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

@Slf4j
@Component
@Scope("prototype")
public class RecordSocketClient extends WebSocketClient {
    private static boolean startFlag = false;

    @Autowired
    private RecordService recordService;

    @Autowired
    private PredictionService predictionService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public RecordSocketClient() throws URISyntaxException {
        super(new URI(KapaCode.WEBSOCKET));
    }

    public static boolean startFlag() {
        return startFlag;
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        log.info("websocket客户端和服务器连接成功");
        //打上标记
        startFlag = true;
    }

    @Override
    public void onMessage(String message) {
        log.info("websocket客户端收到消息={}", message);
    }

    @Override
    public void onMessage(ByteBuffer byteBuffer) {
        String toString = new String(byteBuffer.array());
        KapaSocket kapaSocket = JSONUtil.toBean(toString, KapaSocket.class);
        if (kapaSocket.getCmdMerge() == KapaCmdMerge.KILLER_ROOM) {
            String data = new String(kapaSocket.getData());
            KapaKillerObject kapaKillerObject = JSONUtil.toBean(data, KapaKillerObject.class);
            //获取被噶的房间
            String killerRoom = KapaRoomID.roomName.get(kapaKillerObject.getKillRoms().get(0));
            log.info(killerRoom);
            RecordDTO recordDTO = new RecordDTO();
            recordDTO.setRoom_name(killerRoom);
            recordDTO.setKill_count(1);
            recordService.insertRecordV3(recordDTO);
            predictionService.insertMethod(recordDTO);
            //在预测出来之后插入标记
            Integer games = (Integer) redisTemplate.opsForValue().get("games");
            redisTemplate.opsForValue().set("new", games);
        }

    }

    /**
     * 失败重试
     *
     * @param code
     * @param reason
     * @param remote
     */
    @Override
    public void onClose(int code, String reason, boolean remote) {
        //打上标记，供xxl-job自启动
        log.info("websocket客户端退出连接:" + reason);
        startFlag = false;
    }

    /**
     * 失败重试
     *
     * @param ex
     */
    @Override
    public void onError(Exception ex) {
        log.info("websocket客户端和服务器连接发生错误={}", ex.getMessage());
        ex.printStackTrace();
    }

}
